package orderCus;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import common.Cart;
import common.Customer;
public class LoginServlet extends HttpServlet 
{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException 
	{
		perform(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException 
	{
		perform(req, resp);
	}
	
	private void perform(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException 
	{
		req.setCharacterEncoding("UTF-8");
		StringBuffer msg = new StringBuffer();		//エラー用
		
		String code = req.getParameter("code");
		String pass = req.getParameter("pass");
		//入力チェック
		if(code == null || code.length() == 0)
		{
			msg.append("IDが未入力です。\n");
		}
		if(pass == null || pass.length() == 0)
		{
			msg.append("パスワードが未入力です。\n");
		}
		
		String url = "../index.jsp";
		//ログインチェック
		if(msg == null || msg.length() == 0)
		{
			Customer user = Customer.find_by_code(code);
			
			if(user == null) 
				{
					msg.append("IDまたは\nパスワードが間違っています。");
				}
			else if(!pass.equals(user.getPass()))
			{
					msg.append("IDまたはパスワードが間違っています。");
			}
			else		//エラーがなにもない場合
			{
				Cart cart = new Cart(user);		//ログイン成功時にカートを生成する
				
				HttpSession session = req.getSession();
				session.setAttribute("user", user);
				session.setAttribute("cart", cart);
				url = "/customer/top.jsp";
			}
		}
		//エラーが1つでもあればエラー情報をもって戻る
		req.setAttribute("msg", msg.toString());
		req.setAttribute("code", code);
		req.setAttribute("pass", pass);
		RequestDispatcher dispatcher = req.getRequestDispatcher(url);
		dispatcher.forward(req, resp);
	}
}
